package com.lagou.sqlsession;

import com.lagou.config.SqlCommandType;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public class MapperMethod {
    private Configuration configuration;

    public MapperMethod(Configuration configuration) {
        this.configuration = configuration;
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

    public Object execute(SqlSession sqlSession, Method method, String statementid, Object[] objects) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementid);
        SqlCommandType methodType = mappedStatement.getMethodType();
        switch (methodType){
            case SELECT:
                Type genericReturnType = method.getGenericReturnType();
                if (genericReturnType instanceof ParameterizedType){
                    List<Object> objectList = sqlSession.selectList(statementid, objects);
                    return objectList;
                }
                return sqlSession.selectOne(statementid,objects);
            case INSERT:return sqlSession.insert(statementid,objects);
            case DELETE:return sqlSession.delete(statementid,objects);
            case UPDATE:return sqlSession.update(statementid,objects);
            default:
                throw new RuntimeException("Unknown execution method for: " + methodType.name());
        }
    }


}
